#include "basemodulewithport.h"

BaseModuleWithPort::BaseModuleWithPort(QObject *parent)
    : BaseModule(parent)
{

}

BaseModuleWithPort::~BaseModuleWithPort()
{

}

void BaseModuleWithPort::setPort(BasePort *port)
{
    QMutexLocker locker(m_mutex);
    if (m_port)
    {
        m_port->disconnect();
        m_port->deleteLater();
    }
    m_port = port;

    connect(port, &BasePort::receivePackets,
            this, &BaseModuleWithPort::onParse, Qt::QueuedConnection);
    connect(this, &BaseModuleWithPort::requestSend,
            port, &BasePort::onSend, Qt::QueuedConnection);
}

BasePort *BaseModuleWithPort::getPort(void)
{
    QMutexLocker locker(m_mutex);
    return m_port;
}

void BaseModuleWithPort::setProtocol(BaseProtocol *protocol)
{
    QMutexLocker locker(m_mutex);
    if (m_protocol)
    {
        m_protocol->disconnect();
        m_protocol->deleteLater();
    }
    m_protocol = protocol;
    connect(m_protocol, &BaseProtocol::requestSend, this, &BaseModuleWithPort::requestSend);
    connect(m_protocol, &BaseProtocol::parseCompleted, this, &BaseModuleWithPort::onParseCompleted);
}

BaseProtocol *BaseModuleWithPort::getProtocol()
{
    QMutexLocker locker(m_mutex);
    return m_protocol;
}

void BaseModuleWithPort::onParse(QList<ProtocolPacket> packets)
{
    QMutexLocker locker(m_mutex);
    if (m_enable)
        m_protocol->onWork(packets);
}

void BaseModuleWithPort::onParseCompleted(int id, const QVariant &data)
{

}
